package com.hcrazy.manchester.app.services;

import java.util.List;

import com.hcrazy.manchester.app.jdbc.RadioTagDAO;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.RadioTag;
import com.hcrazy.manchester.app.utils.Constant;

public class RadioTagService {

	private RadioTagDAO radioTagDAO;

	public RadioTagDAO getRadioTagDAO() {
		return radioTagDAO;
	}

	public void setRadioTagDAO(RadioTagDAO radioTagDAO) {
		this.radioTagDAO = radioTagDAO;
	}

	public ErrorMsg addOrUpdateRadioTag(RadioTag tag) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		
		if(tag.getTagId()>0){
			radioTagDAO.updateRadioTag(tag);
		}else{
			radioTagDAO.addRadioTag(tag);
		}
		
		return msg;
	}
	
	/**
	 * 获取二层的树状结构
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public List<RadioTag> getTwoLayerSorts(int type) throws Exception{
		List<RadioTag> list = radioTagDAO.listAllSorts(type);
		RadioTag root = new RadioTag();
		root.setTagId(0);
		for(RadioTag tag:list){
			if(tag.getParentId() == root.getTagId()){
				for(RadioTag tag1:list){
					if(tag1.getParentId() == tag.getTagId()){
						tag.getChildren().add(tag1);
					}
				}
				root.getChildren().add(tag);
			}
		}
		
		return root.getChildren();
	}
	
	public List<RadioTag> getAllSorts(int type,int parentId) throws Exception{
		List<RadioTag> list = radioTagDAO.listAllSorts(type);
		RadioTag root = new RadioTag();
		root.setTagId(parentId);
		setChildren(root, list);
		
		return root.getChildren();
	}
	
	
	private void setChildren(RadioTag root,List<RadioTag> list){
		for(RadioTag tag:list){
			if(tag.getParentId() == root.getTagId()){
				setChildren(tag, list);
				root.getChildren().add(tag);
			}
		}
	}
	
	public RadioTag getSortById(int tagId) throws Exception{
		return radioTagDAO.getById(tagId);
	}
	
	public String delRadioTag(int tagId) throws Exception{
		
		//删除子分类
		radioTagDAO.delRadioTagByParentId(tagId);
		
		//删除本分类
		radioTagDAO.delRadioTag(tagId);
		
		//清空所有父分类不存在的分类
		
		return null;
	}
	
	public List<RadioTag> getByParentId(int parentId) throws Exception{
		return radioTagDAO.getByParentId(parentId);
	}
	
}
